using System;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using InjectionMember=Common.Unity.Configuration.InjectionMember;

namespace Common.Unity.Extensions.Configuration
{
	public class PolicyReference : InjectionMember
	{
		public Type Type { get; set; }

		public string BuildName { get; set; }

		public Type BuildType { get; set; }

		public override Microsoft.Practices.Unity.InjectionMember Create( IUnityContainer container, Type targetType )
		{
			var policy = CreatePolicy( container );
			var result = new PolicyInjection( Type ?? BuildType, policy );
			return result;
		}

		public IBuilderPolicy CreatePolicy( IUnityContainer container )
		{
			using ( var child = container.CreateChildContainer() )
			{
				var result = (IBuilderPolicy)child.Resolve( BuildType, BuildName );
				return result;
			}
		}
	}
}